<template>
  <div class="edit-course-video">
    <el-form
      class="edit-form"
      :model="editForm"
      ref="editForm"
      label-width="70px"
      :rules="rules"
      style="width: 400px; margin: 10px 14px"
    >
      <el-form-item label="课程名称" label-width="106px" prop="courseName">
        <el-input
          v-model="editForm.courseName"
          autocomplete="off"
          :clearable="true"
          @input="changeForm"
        ></el-input>
      </el-form-item>
      <el-form-item label="课程类型" label-width="106px" prop="categoryId">
        <el-select
          v-model="editForm.categoryId"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 140px"
          @input="changeForm"
        >
          <el-option
            v-for="item in courseCategoryArray"
            :key="item.id"
            :label="item.courseCategoryName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面" label-width="106px" prop="cover">
        <div class="insert-cover">
          <div class="cover">
            <img :src="editForm.cover || defaultCover" alt="" />
            <el-upload
              action="zhanweifu"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="changeFile"
            >
              <span v-loading="uploadLoading"></span>
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="视频" label-width="106px" prop="video">
        <div class="insert-video">
          <el-upload
            action="zhanweifu"
            :auto-upload="false"
            :on-change="changeVideoFile"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传mp4文件，且不超过15M
            </div>
          </el-upload>
          <span v-loading="uploadVideoLoading"></span>
        </div>
      </el-form-item>
      <el-form-item label="点击次数" label-width="106px" prop="clickCount">
        <el-input
          disabled
          v-model="editForm.clickCount"
          autocomplete="off"
          style="width: 100px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          v-show="isShow"
          type="success"
          @click="update"
          :loading="updateLoading"
          >更新</el-button
        >
      </el-form-item>
    </el-form>
    <div class="video">
      <VideoView :videoSrc="editForm.video"></VideoView>
    </div>
  </div>
</template>

<script>
import VideoView from "@/components/VideoView.vue";
import defaultCover from "@/assets/defaultCover.png";
import { uploadFile } from "@/api/common";
import { getAllCourseCategory } from "@/api/admin/courseCategory";
import { getCourseVideoById, updateCourseVideo } from "@/api/admin/courseVideo";
export default {
  name: "EditCourseVideoView",
  data() {
    return {
      // 课程类型
      courseCategoryArray: [],
      editForm: {},
      copyForm: {},
      rules: {
        courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择课程类型", trigger: "change" },
        ],
        cover: [{ required: true, message: "请上传封面", trigger: "blur" }],
        video: [{ required: true, message: "请上传视频", trigger: "blur" }],
      },
      isShow: false,
      updateLoading: false,
      defaultCover,
      uploadLoading: false,
      uploadVideoLoading: false,
      fileList: [],
      videoSrc: "",
    };
  },
  props: ["id"],
  created() {
    this.getCourseCategory();
    this.getCourseVideoInfo();
  },
  components: {
    VideoView,
  },
  methods: {
    // 检测表单数据是否修改
    changeForm() {
      const objectEqual =
        JSON.stringify(this.editForm) === JSON.stringify(this.copyForm);
      if (!objectEqual) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    // 获取课程视频信息
    async getCourseVideoInfo() {
      const res = await getCourseVideoById(this.id);
      this.editForm = Object.assign({}, res.data);
      this.copyForm = Object.assign({}, res.data);
    },
    // 获取所有课程分类
    async getCourseCategory() {
      const res = await getAllCourseCategory();
      this.courseCategoryArray = res.data;
    },
    // 更新数据
    update() {
      this.$refs.editForm.validate(async (v) => {
        if (v) {
          try {
            this.updateLoading = true;
            const res = await updateCourseVideo(this.editForm);
            this.$router.push({
              name: "AdminCourseVideo",
            });
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
    // 选择文件，上传封面
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器
      // console.log("上传到服务器,返回图片路径赋值给insertForm.cover");
      this.uploadLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const res = await uploadFile(formData);
        this.editForm.cover = res.data;
        this.changeForm();
      } finally {
        this.uploadLoading = false;
      }
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
    // 上传视频
    async changeVideoFile(file) {
      const bool = this.verifyVideoFormat(file);
      if (!bool) {
        return;
      }
      if (this.fileList.length > 0) {
        this.fileList.pop();
      }
      this.uploadVideoLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const res = await uploadFile(formData);
        this.editForm.video = res.data;
        this.fileList.push({ name: file.raw.name });
        this.changeForm();
      } finally {
        this.uploadVideoLoading = false;
      }
    },
    // 上传视频校验
    verifyVideoFormat(file) {
      const isMP4 = file.raw.type === "video/mp4";
      // 大小小于15M
      const isLt15M = file.raw.size / 1024 / 1024 < 15;
      if (!isMP4) {
        this.$message.error("上传视频只能是 mp4 格式!");
        return false;
      }
      if (!isLt15M) {
        this.$message.error("上传视频大小不能超过 15MB!");
        return false;
      }
      return isMP4 && isLt15M;
    },
  },
};
</script>

<style lang="less" scoped>
.edit-course-video {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  .edit-form {
    height: 100%;
    .insert-cover {
      position: relative;
      width: 100%;
      height: 160px;
      .cover {
        width: 134px;
        height: 134px;
        position: relative;
        top: 50%;
        left: 21%;
        transform: translate(-50%, -50%);
        img {
          width: 100%;
          height: 100%;
          cursor: pointer;
        }
        span {
          position: absolute;
          top: 50%;
          left: 50%;
          width: 134px;
          height: 134px;
          transform: translate(-50%, -50%);
          &::before {
            content: "上传封面";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 134px;
            height: 134px;
            background-color: rgba(0, 0, 0, 0.06);
            text-align: center;
            line-height: 134px;
            cursor: pointer;
            opacity: 0;
            visibility: hidden;
            z-index: 1;
            color: black;
          }
          &:hover::before {
            opacity: 1;
            visibility: visible;
          }
        }
      }
    }
    .insert-video {
      position: relative;
      span {
        position: absolute;
        top: 23%;
        left: 28%;
        border: 1px solid;
      }
      .el-upload__tip {
        margin-top: 0;
      }
      /deep/.el-upload-list__item:first-child {
        margin-top: 0;
      }
    }
  }
  .video {
    margin-left: 100px;
  }
}
// 解决下拉框显示不完整问题
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
  margin-bottom: 0 !important;
}
</style>